package com.beijing.baseaction;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * Description: 定义封装所有action的基类 
 * Company: 
 * author:70kg 
 * date:2018年1月5日
 */
public class BaseAction extends ActionSupport implements Preparable {

    protected transient final Log log = LogFactory.getLog(getClass());

    private static final long serialVersionUID = 1L;

    public static final String CANCEL = "cancel";
    public static final String SUCCESS = "success";
    public static final String INPUT = "input";
    public static final String ERROR = "error";
    public static final String SYSERROR = "syserror";
    public static final String LOGIN = "login";
    public static final String SYSUCCESS = "sysuccess";
    public static final String SYSINFO = "sysinfo";

    public void prepare() throws Exception {

    }

    /**
     * 取得当前request
     */
    protected HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    /**
     * 取得session
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 取得response
     */
    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * 从spring容器中取得bean
     */
    public Object getBean(String name) {
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getRequest().getSession().getServletContext());
        return ctx.getBean(name);
    }

    /**
     * 向reponse中写入str
     * 
     * @param str
     * @throws IOException
     */
    protected void writeString(String str) throws IOException {
        HttpServletResponse response = getResponse();
        response.setContentType("text/xml; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.write(str);
        out.close();
    }

    /**
     * 向reponse中写入str
     * 
     * @param str
     * @throws IOException
     */
    protected void writeJson(String str) throws IOException {
        HttpServletResponse response = getResponse();
        response.setContentType("application/json; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.write(str);
        out.flush();
        out.close();

    }
}
